#include "search.h"
#include "ui_search.h"
#define IP "192.168.255.255"

Search::Search(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Search)
{
    ui->setupUi(this);
    ui->m_port->setPlaceholderText("port:");

    m_socket = new QUdpSocket(this);
    socket = new QTcpSocket(this);

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&Search::hartTimerSlot);
    connect(m_socket,SIGNAL(readyRead()),this,SLOT(udpRecvSlot()));
}

Search::~Search()
{
    delete ui;
    m_socket->close();
}

void Search::on_m_search_clicked()
{
    unsigned short port = ui->m_port->text().toUShort();
    QHostAddress broadcastAddress(IP);//广播地址
    QByteArray datagram = "group";//发送数据
    if(m_socket->writeDatagram(datagram,datagram.size(),broadcastAddress,port))
    {
        ui->m_text->append("广播成功");
        ui->m_text->append("搜索中....");
    }
    else{
        ui->m_text->append("广播失败");
    }
}

void Search::dataSlots()
{
    QByteArray ba = socket->readAll();
    QString str = QString::fromUtf8(ba);
    ui->m_text->append(str);
    if(str == "yes")
    {
        qDebug() << "连接成功";
        QMessageBox::information(this,"信息","tcp连接成功");
//        ui->m_link->setStyleSheet(stylesheet1);
    }
    else
    {

    }
}

void Search::hartTimerSlot()
{
    QJsonObject json;
    json["type"] = 3;
    QJsonDocument jsonDoc(json);
    QByteArray jsonData = jsonDoc.toJson();
    socket->write(jsonData);
    if(socket->waitForBytesWritten())
    {
        ui->m_text->append("心跳包发送成功");
    }
    else
    {
        ui->m_text->append("心跳包发送失败");
    }
}
//开始发送心跳包
void Search::on_m_button_start_clicked()
{
    timer->start(1000);
}
//停止发送心跳包
void Search::on_m_button_stop_clicked()
{
    timer->stop();
}
//广播接收数据
void Search::udpRecvSlot()
{
    while(m_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(m_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        m_socket->readDatagram(datagram.data(),datagram.size(),&sender,&senderPort);
        tcpip = sender.toString();
        qDebug() << "Received datagram from:" << sender.toString() << datagram.data();
        ui->m_text->append(sender.toString());
        m_socket->close();//关闭广播
    }
}
//进行tcp连接
void Search::on_pushButton_clicked()
{
    socket->connectToHost(tcpip,8080);
    if(!socket->waitForConnected(1000))
    {
        ui->m_text->append("TCP连接失败");
        ui->m_link->setText("连接失败");
    }
    else
    {
        qDebug()<<"成功";
        connect(socket,&QTcpSocket::readyRead,
                        this,&Search::dataSlots);
        ui->m_link->setChecked(true);
        ui->m_link->setText("连接成功");
    }
}




//    m_socket->connectToHost(IP,port);
//    if(!m_socket->waitForConnected(1000))
//    {
//        ui->m_text->append("搜寻失败");
//    }
//    else
//    {
//        ui->m_text->append("搜寻成功");
//        connect(m_socket,&QTcpSocket::readyRead,
//                this,&Search::dataSlots);
//    }
